/* **************************************************************************/
/*COPYRIGHT CCWIN-IN ALL RIGHTS RESERVED. THIS IS AN UNPUBLISHED WORK.      */
/*V8:ConvertMode=Report                                                     */
/*V8:WebEnabled=Yes                                                         */
/*V8:RunMode=Character,Windows                                              */
/*EXTRACTING DATA FROM MFG/PRO                                              */
/****************************************************************************/
/* PROCEDURE NAME        : xxcustomerexptapi.p                              */
/* PROCEDURE TYPE        : API export Process                               */
/* DESCRIPTION           : customer export Process                          */
/*                                                                          */     
/* INCLUDE FILES         :                                                  */
/* CALLED BY             :                                                  */
/* CALLED PROCEDURES     :                                                  */
/****************************************************************************/
/* CREATED BY            : Gaoyan                                28-Jul-24  */
/****************************************************************************/ 
/****************************************************************************/
/****************************************************************************/

{us/mf/mfdtitle.i}
{us/bbi/gplabel.i}
{us/wb/wbrp01.i}
{xxjson.i}
{xxcimload.i}
{us/gl/glsec.i}

{proxy/bcinvoiceapmatchingdef.i}


&GLOBAL-DEFINE TimeStamp1 STRING(Year(today),"9999") + STRING(month(today),"99") + STRING(day(today),"99") + substring(string(time,"hh:mm:ss"),1,2) + substring(string(time,"hh:mm:ss"),4,2) + substring(string(time,"hh:mm:ss"),7,2)



define input parameter vc_inputjson             as character format "x(60)" no-undo.
define input parameter vc_outputjson            as character format "x(60)" no-undo.
define input parameter vc_import                as logical  no-undo.


define stream f_log.
define stream f_cim.
define variable v_quote               as character initial """"   no-undo.
define variable v_default             as character initial "-"    no-undo.
define variable v_space               as character initial " "    no-undo.
define variable v_log                 as character                no-undo.
define variable v_cim                 as character                no-undo.
define variable v_fline               as character                no-undo.
define variable v_errorstatus         as logical                  no-undo.
define variable v_toterrorstatus         as logical                  no-undo.
define variable v_errstring           as character                no-undo.
define variable v_status              as character                no-undo.

define variable v_entity              like si_entity              no-undo.

define variable vi_filecount          as integer                  no-undo.
define variable vc_filename           as character                no-undo.
define variable vc_topath             as character                no-undo.
define variable v_runproagram        as character                no-undo.
define variable vc_traceid            as character                no-undo.



define variable v_prefix      as character        format "x(20)"     no-undo.
define variable v_extn        as character                           no-undo.
define variable v_outpath     as character        format "x(50)"     no-undo.
define variable v_inpath      as character        format "x(50)"     no-undo.
define variable v_sftpip      as character        format "x(20)"     no-undo.
define variable v_sftpid      as character        format "x(20)"     no-undo.
define variable v_sftppw      as character        format "x(15)"     no-undo.
define variable v_infile      as character        format "X(40)"     no-undo.
define variable v_infile1     as character        format "X(40)"     no-undo.
define variable v_file1       as character        format "x(20)"     no-undo.
define variable v_file        as character        format "x(50)"     no-undo.
define variable dir-file      as character                           no-undo.
define variable v_logfile     as character        format "x(50)"     no-undo.

define variable m_line1       as character                           no-undo.
define variable v_name        as character                           no-undo.
define variable m_quote       as character        initial '"'        no-undo.
define variable m_space       as character        initial ' '        no-undo.
define variable errline       as character        format "x(80)"     no-undo.
define variable errfile       as character                           no-undo.
define variable errflpt       as character                           no-undo.
define variable stdfile       as character                           no-undo.
define variable outfile       as character                           no-undo.
define variable m_arg1        as character                           no-undo.
define variable v_tmpstr      as character                           no-undo.
define variable v_count       as integer                             no-undo.
define variable v_flcnt       as integer                             no-undo.
define variable m_success     as logical          format "YES/NO"    no-undo.
define variable m_success1    as logical          format "YES/NO"    no-undo.
define variable v_import         as logical       init   "YES"       no-undo.
define variable v_error       as logical                             no-undo.
define variable m_content     as logical          init   "NO"        no-undo.
define variable errflag       as logical                             no-undo.
define variable v_ref         as logical          init   "NO"        no-undo.
define stream   data-stream.
define variable m_entity      like si_entity                         no-undo.
define variable l_fdata       as character                           no-undo.
define variable i             as integer                             no-undo.
define variable m_tmpstr      as character        format "X(150)"    no-undo.
define variable m_voucher     like vo_mstr.vo_ref                    no-undo.
define variable m_status      as logical                             no-undo.
define variable entity_ok     as logical                             no-undo.
define variable m_closed      as logical                             no-undo.
define variable v_trans_qty   as deci                                no-undo.
define variable v_vou_qty     as deci                                no-undo.
define variable v_opn_qty     as deci                                no-undo.
define variable v_batch_run   as LOGI                                no-undo.
define variable v_po_nums     as char             format "X(150)"    no-undo.
define variable m_year        as inte                                no-undo.
define variable v_errmsg      as character        format "x(150)"    no-undo.
define variable v_poamt       as decimal                             no-undo.
define variable v_invamt      as decimal                             no-undo.
define variable inv_cnt as integer    no-undo.
define variable receiver_counter as integer    no-undo.
define variable acc_counter as integer    no-undo.
define variable m_errfile as character  no-undo.
define variable v_cnt     as integer    no-undo.

/* ======== FOR API ========= */
define variable viReturn                     as integer     no-undo.
define variable ilReturnDataset              as logical     no-undo.
define variable ilPartialUpdate              as logical     no-undo.
define variable icPartialUpdateExceptionList as character   no-undo.
define variable ocPrimaryKey                 as character   no-undo.
define variable ocRowid                      as character   no-undo.
define variable oiDraftInstance              as integer     no-undo.
define variable ocPrimaryKeyName             as character   no-undo.
define variable vho                          as handle.
define variable oiReturnStatus               as integer     no-undo.

define variable lvi_row_id                   as integer     no-undo.
define variable v_desc as character no-undo.
define variable v_basedebit as decimal no-undo.

define stream logStrm.
define stream errStrm.

/*For Tax*/
define variable v_taxEnv                     as   character                         no-undo.
define variable v_taxType                    as   character                         no-undo.
define variable v_taxRate                    as   decimal                           no-undo.
define variable v_taxClass                   as   character                         no-undo.
define variable v_taxUsage                   as   character                         no-undo.
define variable v_vatCode                    as   character                         no-undo.
define variable v_taxAccount                 as   character                         no-undo.
define variable v_taxCNAccount               as   character                         no-undo.
define variable v_tzFrom                     as   character                         no-undo.
define variable v_tzTo                       as   character                         no-undo.
define variable v_taxCode                    as   character                         no-undo.
define variable v_taxable                    as   logical                           no-undo.
define variable v_taxExcluded                as  logical                            no-undo.
define variable v_noTax                      as   character        init "NON-TAX"   no-undo.

define variable m_apbatch     like apc_batch                no-undo.

define temp-table tt_tAPMatchingCIAPM like tAPMatchingCIAPM 
          field  tAPMatchingCIAPM_traceid as character  
          field  tAPMatchingCIAPM_dataid as character 
          
          .  
          
define temp-table tt_tCInvoiceCIAPM like tCInvoiceCIAPM 
          field  tCInvoiceCIAPM_traceid as character  
          field  tCInvoiceCIAPM_dataid as character 
          field  tCInvoiceCIAPM_userid as character 
          field  tCInvoiceCIAPM_taxaccount as character 
          field  tCInvoiceCIAPM_varaccount as character 
          field  tCInvoiceCIAPM_taxenv    as character 
          field  tCInvoiceCIAPM_taxclass    as character 
          field  tCInvoiceCIAPM_taxusage    as character 
          field  tCInvoiceCIAPM_taxamount as decimal 
          field  tCInvoiceCIAPM_invamount as decimal 
          field  tCInvoiceCIAPM_taxrate as decimal 
          . 

define temp-table tt_tAPMatchingCostCIAPM like tAPMatchingCostCIAPM  
          field  tAPMatchingCostCIAPM_traceid as character  
          field  tAPMatchingCostCIAPM_dataid as character
          .


define temp-table tt_tAPMatchingCostSafCIAPM like tAPMatchingCostSafCIAPM.

define temp-table tt_CInvoiceAdditional no-undo
   field tt_invoicenumber    as character
   field tt_purchasetype     as character 
   field tt_userid           as character
   field tt_rmk              as character
   field tt_totinvamt        as decimal
   field tt_tottaxamt        as decimal
   field tt_qadinvamt        as decimal
   field tt_qadtaxamt        as decimal
   field tt_taxrate          as decimal
   field tt_currency         as character
   field tt_taxacc       like GL.GLCode
   field tt_glacc        like GL.GLCode
   field tt_division     like division.divisioncode
   field tt_costcenter   like costcentre.costcentrecode
   field tt_parentid         as character
   field tt_allcamt          as decimal.

define variable v_site                       like si_site  initial "2000"                no-undo.
define variable v_supplier                   like creditor.creditorcode    no-undo.
define variable v_supplier1                  like creditor.creditorcode    no-undo.
define variable R_import                     as logical     init   "No"    no-undo.

DEFINE VARIABLE li_access                    AS    INTEGER                 NO-UNDO.
define variable l_error                      as character                  no-undo.
define variable taxacc                      as character                  no-undo.
define variable glacc                       as character                  no-undo.
define variable vc_taxtype                       as character                  no-undo.
define variable vd_tax_pct                       as decimal                  no-undo.

/*
  DEFINE DATASET dsSupplierInvoice FOR tCInvoiceCIAPM, tt_tAPMatchingCIAPM, tt_tAPMatchingCostCIAPM
            PARENT-ID-RELATION pid FOR tCInvoiceCIAPM, tt_tAPMatchingCIAPM 
            PARENT-ID-FIELD pid
            PARENT-ID-RELATION pid1 FOR tCInvoiceCIAPM,  tt_tAPMatchingCostCIAPM
            PARENT-ID-FIELD pid.
          */
     DEFINE DATASET dsSupplierInvoice FOR tt_tCInvoiceCIAPM, tt_tAPMatchingCIAPM,tt_tAPMatchingCostCIAPM
  
            DATA-RELATION rel1 FOR tt_tCInvoiceCIAPM, tt_tAPMatchingCIAPM RELATION-FIELDS(tc_RowId,tc_ParentRowid)
            DATA-RELATION rel2 FOR tt_tCInvoiceCIAPM, tt_tAPMatchingCostCIAPM RELATION-FIELDS(tc_RowId,tc_ParentRowid)
       
            .
            
   hdataset = dataset dsSupplierInvoice:HANDLE.             
/** Get next rc_RowId fuction **/

function fiGetNextRowID returns decimal:
        lvi_row_id = lvi_row_id + 1000.
        return lvi_row_id.
        end function. /* fiGetNextRowID */ 
		



mainloop:
repeat on error undo mainloop, leave mainloop:    


  /* Output and Batch Input */
   
   {us/xx/xxworkpath_e.i &outbound=YES &inbound=no &archive=YES}

    assign
      m_outpath     = m_outpath + "sinv/"
      m_archpath    = m_archpath + "sinv/"
      m_successpath = m_successpath + "sinv/"
      m_errorpath   = m_errorpath + "sinv/"
      m_workpath    = m_workpath + "sinv/".
      

      empty temp-table tt_tAPMatchingCIAPM.
      empty temp-table tt_tCInvoiceCIAPM.
      empty temp-table tt_tAPMatchingCostCIAPM.
      empty temp-table tt_tAPMatchingCostSafCIAPM.
      empty temp-table tt_CInvoiceAdditional.
   


   v_runproagram = "".
   vc_traceid = "".
   
   /* Load item master data from JSON  */ 
   vc_outputjson = replace(vc_inputjson,".json",".run.out.json").   
   run loadjsonfile(input vc_inputjson,
                    input vc_outputjson,
                    output vl_RetOK).
   if vl_RetOK then
   do:
      find first tt_tCInvoiceCIAPM no-error.
      assign vc_traceid = tt_tCInvoiceCIAPM.tc_RowId.
   end.
   

	  
	find code_mstr where code_domain = global_domain
	                 and code_fldname = "xxinvoicefromscp"
					 and code_value   = "taxacc"
					 no-lock no-error.
	assign taxacc = code_cmmt.
	  
	find code_mstr where code_domain = global_domain
	                 and code_fldname = "xxinvoicefromscp"
					 and code_value   = "glacc"
					 no-lock no-error.
	assign glacc = code_cmmt.	
	
  /** calculate tax and invoice amount variance */
  output to /apps/eai/work/cim/apmatch.log.
   for each tt_tCInvoiceCIAPM break by tt_tCInvoiceCIAPM.tc_Rowid.
         
          run getTaxDet(input  tt_tCInvoiceCIAPM.tcCreditorCode ,      
                        input  tt_tCInvoiceCIAPM.tcCompanyCode,
                        input  tt_tCInvoiceCIAPM.tCInvoiceCIAPM_taxusage, 
                        input  tt_tCInvoiceCIAPM.tCInvoiceCIAPM_taxclass,
                        input  tt_tCInvoiceCIAPM.ttCInvoicePostingDate,
                        input  yes ,
                        output v_taxEnv,     
                        output v_taxType,
                        output v_taxRate,    
                        output v_vatCode,
                        output v_taxAccount, 
                        output v_tzFrom,
                        output v_tzTo,       
                        output v_taxCode,
                        output v_taxCNAccount).
             
         
         Create tt_CInvoiceAdditional.
			assign 
			       tt_CInvoiceAdditional.tt_invoicenumber = tt_tCInvoiceCIAPM.tcCInvoiceReference  
				    tt_CInvoiceAdditional.tt_parentid      = tt_tCInvoiceCIAPM.tc_Rowid
				    tt_CInvoiceAdditional.tt_userid        = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_userid
				    tt_CInvoiceAdditional.tt_totinvamt     = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_invamount
				    tt_CInvoiceAdditional.tt_tottaxamt     = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_taxamount
				    tt_CInvoiceAdditional.tt_taxrate       = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_taxrate
				    tt_CInvoiceAdditional.tt_taxacc        = taxacc /* tt_tCInvoiceCIAPM.tCInvoiceCIAPM_taxaccount */
				    tt_CInvoiceAdditional.tt_glacc         = glacc /* tt_tCInvoiceCIAPM.tCInvoiceCIAPM_varaccount */
				    tt_CInvoiceAdditional.tt_currency      = tt_tCInvoiceCIAPM.tcCInvoiceCurrencyCode
				    tt_CInvoiceAdditional.tt_costcenter    = tt_tCInvoiceCIAPM.tcCInvoiceCostCentreCode
				    tt_CInvoiceAdditional.tt_division      = tt_tCInvoiceCIAPM.tcCInvoiceDivisionCode .
		          
				  
   
       for each tt_tAPMatchingCIAPM where tt_tAPMatchingCIAPM.tc_ParentRowid = tt_tCInvoiceCIAPM.tc_Rowid.
          vd_tax_pct = 0.
	       find prh_hist where prh_domain    = global_domain
          /*
		                    and prh_nbr       = tt_tAPMatchingCIAPM.tcPurchaseOrderNumber
                          */
                          and prh_line      = tt_tAPMatchingCIAPM.tiPurchaseOrderLineNumber 
                          and prh_receiver  = tt_tAPMatchingCIAPM.tcReceiverNumber 
							     no-lock no-error.
           find tx2d_det no-lock  where tx2d_nbr = prh_nbr
                                            and tx2d_line = prh_line
                                            and tx2d_domain = prh_domain
                                            and tx2d_ref = prh_receiver
                                            no-error.
              if available tx2d_det then 
              do:
                  
                        find tx2_mstr where tx2_domain = prh_domain
                                        and tx2_tax_code = tx2d_tax_code
                                          no-lock no-error.                       
			 
          if available tx2_mstr  then
          assign vd_tax_pct = tx2_tax_pct.
          else 
          assign vd_tax_pct = 0.
         end. /*   if available tx2d_det then  */
         
		   find tt_CInvoiceAdditional where tt_CInvoiceAdditional.tt_parentid = tt_tCInvoiceCIAPM.tc_Rowid no-error.
            assign tt_CInvoiceAdditional.tt_qadtaxamt =  tt_CInvoiceAdditional.tt_qadtaxamt +           		   
			                                                round(round(tt_tAPMatchingCIAPM.tdMatchQty  *  
                                                         tt_tAPMatchingCIAPM.tdMatchUnitPrice,2) * 
                                                         vd_tax_pct / 100 , 2)
               	 tt_CInvoiceAdditional.tt_qadinvamt =  tt_CInvoiceAdditional.tt_qadinvamt + 
				                                             round(tt_tAPMatchingCIAPM.tdMatchQty  *  
                                                         tt_tAPMatchingCIAPM.tdMatchUnitPrice,2).

            
       end. /* for each tt_tAPMatchingCIAPM where  */
	   
       find tt_CInvoiceAdditional where tt_CInvoiceAdditional.tt_parentid = tt_tCInvoiceCIAPM.tc_Rowid  no-error.
	   
	    if  tt_CInvoiceAdditional.tt_tottaxamt - tt_CInvoiceAdditional.tt_qadtaxamt  <> 0 then do:
       
         

				find first tx2_mstr where tx2_mstr.tx2_domain    = Global_domain
					                   and tx2_mstr.tx2_tax_type  = v_taxType
											 and tx2_mstr.tx2_pt_taxc   = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_taxclass
                                  and tx2_mstr.tx2_tax_pct   = tt_CInvoiceAdditional.tt_taxrate
											 and tx2_mstr.tx2_tax_usage = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_taxusage
											 and tx2_mstr.tx2_effdate   <= tt_tCInvoiceCIAPM.ttCInvoicePostingDate
											 and (tx2_mstr.tx2_exp_date  = ? or 
										         tx2_mstr.tx2_exp_date >= tt_tCInvoiceCIAPM.ttCInvoicePostingDate)
										    no-lock no-error.
                                  
				 for first GL where GL.GLTYPECODE = "VAT"
                            and GL.Glcode = tt_CInvoiceAdditional.tt_taxacc
                            no-lock:
             end.
                              
             if available GL and available tx2_mstr
             then do:					 
                      find first txe_mstr where txe_mstr.txe_tax_env = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_taxenv
                                            no-lock no-error.
             
             
             
                      create tt_tAPMatchingCostCIAPM.
                      assign
                         tt_tAPMatchingCostCIAPM.tcGLCode             = tt_CInvoiceAdditional.tt_taxacc
                         tt_tAPMatchingCostCIAPM.tcCurrencyCode      = tt_CInvoiceAdditional.tt_currency
                         tt_tAPMatchingCostCIAPM.tcTaxEnvironment     = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_taxenv
                         tt_tAPMatchingCostCIAPM.tcTaxUsage           = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_taxusage
                         tt_tAPMatchingCostCIAPM.tcTaxClass           = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_taxclass
                         tt_tAPMatchingCostCIAPM.ttTaxPointDate       = tt_tCInvoiceCIAPM.ttCInvoicePostingDate
                         tt_tAPMatchingCostCIAPM.tcTaxTransactionType = "55"
                         tt_tAPMatchingCostCIAPM.tcTransactionType    = "Purchase"
                         tt_tAPMatchingCostCIAPM.tc_Rowid             = string(fiGetNextRowID())
                         tt_tAPMatchingCostCIAPM.tc_ParentRowid       = tt_CInvoiceAdditional.tt_parentid
                         tt_tAPMatchingCostCIAPM.tc_Status            = "N"
                         tt_tAPMatchingCostCIAPM.tcPostingVatInOut    = "Input"
                         tt_tAPMatchingCostCIAPM.tcFromTaxZone        = txe_mstr.txe_zone_from
                         tt_tAPMatchingCostCIAPM.tcToTaxZone          = txe_mstr.txe_zone_to
                         tt_tAPMatchingCostCIAPM.tcTaxType            = v_taxType
                         tt_tAPMatchingCostCIAPM.tcPostingVatCode     = tx2_mstr.tx2_tax_code
                         tt_tAPMatchingCostCIAPM.tcPostingVatDomain   = global_domain
                         tt_tAPMatchingCostCIAPM.tcCurrencyCode       = tt_CInvoiceAdditional.tt_currency
                         tt_tAPMatchingCostCIAPM.tdVatDebitTC  = tt_CInvoiceAdditional.tt_tottaxamt - tt_CInvoiceAdditional.tt_qadtaxamt
                         tt_tAPMatchingCostCIAPM.tdVatDebitLC  = tt_CInvoiceAdditional.tt_tottaxamt - tt_CInvoiceAdditional.tt_qadtaxamt
                         tt_tAPMatchingCostCIAPM.tdVatDebitCC  = tt_CInvoiceAdditional.tt_tottaxamt - tt_CInvoiceAdditional.tt_qadtaxamt
                         v_basedebit = (tAPMatchingCostCIAPM.tdVatDebitLC * 100) / tAPMatchingCostCIAPM.tdVatDebitLC  
                         v_basedebit = round(v_basedebit,2)
                         tt_tAPMatchingCostCIAPM.tdBaseDebitTC = v_basedebit
                         tt_tAPMatchingCostCIAPM.tdBaseDebitLC = v_basedebit
                         tt_tAPMatchingCostCIAPM.tdBaseDebitCC = v_basedebit.	
				end.	/* if available GL */		
            else do:
                      create tt_tAPMatchingCostCIAPM.
                      assign
                         tt_tAPMatchingCostCIAPM.tcGLCode          = tt_CInvoiceAdditional.tt_taxacc
                         tt_tAPMatchingCostCIAPM.tcDivisionCode    = tt_CInvoiceAdditional.tt_division
                         tt_tAPMatchingCostCIAPM.tcCostCentreCode  = tt_CInvoiceAdditional.tt_costcenter
                         tt_tAPMatchingCostCIAPM.tcCurrencyCode    = tt_CInvoiceAdditional.tt_currency
                         tt_tAPMatchingCostCIAPM.tcProjectCode     = ""
                         tt_tAPMatchingCostCIAPM.tcTaxEnvironment  = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_taxenv
                         tt_tAPMatchingCostCIAPM.tcTaxUsage        = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_taxusage
                         tt_tAPMatchingCostCIAPM.tcTaxClass        = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_taxclass
                         tt_tAPMatchingCostCIAPM.tc_Rowid          = string(fiGetNextRowID())
                         tt_tAPMatchingCostCIAPM.tc_ParentRowid    = tt_CInvoiceAdditional.tt_parentid
                         tt_tAPMatchingCostCIAPM.tc_Status         = "N"
                         tt_tAPMatchingCostCIAPM.tdDebitTC  = tt_CInvoiceAdditional.tt_tottaxamt - tt_CInvoiceAdditional.tt_qadtaxamt
                         tt_tAPMatchingCostCIAPM.tdDebitLC  = tt_CInvoiceAdditional.tt_tottaxamt - tt_CInvoiceAdditional.tt_qadtaxamt
                         tt_tAPMatchingCostCIAPM.tdDebitCC  = tt_CInvoiceAdditional.tt_tottaxamt - tt_CInvoiceAdditional.tt_qadtaxamt.
                         
	           end. /* NOT VAT account */    
              
	   end. /* if  tt_CInvoiceAdditional.tt_qadtaxamt - tt_CInvoiceAdditional.tt_tottaxamt <> 0 then do: */
	   
	   if  tt_CInvoiceAdditional.tt_totinvamt - tt_CInvoiceAdditional.tt_qadinvamt <> 0 then do:
       put  tt_CInvoiceAdditional.tt_totinvamt - tt_CInvoiceAdditional.tt_qadinvamt  skip .
                      create tt_tAPMatchingCostCIAPM.
                      assign
                         tt_tAPMatchingCostCIAPM.tcGLCode          = tt_glacc
                         tt_tAPMatchingCostCIAPM.tcDivisionCode    = tt_CInvoiceAdditional.tt_division
                         tt_tAPMatchingCostCIAPM.tcCurrencyCode    = tt_CInvoiceAdditional.tt_currency
                         tt_tAPMatchingCostCIAPM.tcCostCentreCode  = tt_CInvoiceAdditional.tt_costcenter
                         tt_tAPMatchingCostCIAPM.tcProjectCode     = ""
                         tt_tAPMatchingCostCIAPM.tcTaxEnvironment  = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_taxenv
                         tt_tAPMatchingCostCIAPM.tcTaxUsage        = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_taxusage
                         tt_tAPMatchingCostCIAPM.tcTaxClass        = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_taxclass
                         tt_tAPMatchingCostCIAPM.tc_Rowid          = string(fiGetNextRowID())
                         tt_tAPMatchingCostCIAPM.tc_ParentRowid    = tt_CInvoiceAdditional.tt_parentid
                         tt_tAPMatchingCostCIAPM.tc_Status         = "N"
                         tt_tAPMatchingCostCIAPM.tdDebitTC         =  tt_CInvoiceAdditional.tt_totinvamt - tt_CInvoiceAdditional.tt_qadinvamt
                         tt_tAPMatchingCostCIAPM.tdDebitLC         =  tt_CInvoiceAdditional.tt_totinvamt - tt_CInvoiceAdditional.tt_qadinvamt
                         tt_tAPMatchingCostCIAPM.tdDebitCC         =  tt_CInvoiceAdditional.tt_totinvamt - tt_CInvoiceAdditional.tt_qadinvamt.	   
	                 
	   end. /* tt_CInvoiceAdditional.tt_qadinvamt - tt_CInvoiceAdditional.tt_totinvamt <> 0 then do: */
      
      
   end. /* for each tt_tCInvoiceCIAPM break by tt_tCInvoiceCIAPM.tc_Rowid. */
   
 
  /*** below is validations  **/
  /** Validate Entity code **/
  /** Supplier code/PO number/Currency/sub account **/
  /** cost centre/ payment reference/ ap period  **/
  
     v_toterrorstatus = no. 
        
     /** Validate Company Code */
	 for each tt_tCInvoiceCIAPM :

	 for first Domains no-lock where DomainCode = global_domain,
        first Company of Domains no-lock
              where CompanyCode = tt_tCInvoiceCIAPM.tcCompanyCode:
    end.
     
     if not available Company
     then do:
     
        /*Not a valid company*/
        create api_status.
        assign api_status.data_seq     = 0
               api_status.return_status  = "FAILED"
               api_status.message_type = "Pre-validation"
               api_status.message_string  = gettermlabel("COMPANY_CODE",8) + gettermlabel("DOES_NOT_EXIST",6)                                       
               api_status.traceid = vc_traceid. 
           
     end. /*IF NOT AVAILABLE Company THEN*/
     
      /* Supplier Code */
     for first Creditor
        where CreditorCode = tt_tCInvoiceCIAPM.tcCreditorCode
     no-lock:
     end.
     
     if not available Creditor
     then do:
        /* Supplier code does not exist*/
        create api_status.
        assign api_status.data_seq     = 0
               api_status.return_status  = "FAILED"
               api_status.message_type = "Pre-validation"
               api_status.message_string  = gettermlabel("SUPPLIER_CODE",8) + gettermlabel("DOES_NOT_EXIST",6)                                       
               api_status.traceid = vc_traceid. 
     end.
     
    
     /* Posting date validation */
     for last Period of company
        where  PeriodStatus      = "PERIODOPEN"
        and PeriodStartDate     <= date(tt_tCInvoiceCIAPM.ttCInvoicePostingDate)
        and PeriodEndDate       >= date(tt_tCInvoiceCIAPM.ttCInvoicePostingDate)
        and PeriodIsPostingPurchAllow no-lock: /*157231 Added N0-LOCK*/
     end.
     
     if not available period
     then do:
        /*25057 Period closed*/
        create api_status.
        assign api_status.data_seq     = 0
               api_status.return_status  = "FAILED"
               api_status.message_type = "Pre-validation"
               api_status.message_string  = gettermlabel("GL_PERIOD",8) + gettermlabel("CLOSE",6)                                       
               api_status.traceid = vc_traceid. 
     end.

        
     /* TSMReference */
	 if can-find (first code_mstr no-lock where code_mstr.code_domain  = global_domain
                                  and code_mstr.code_fldname = "XX_PAYREFSEPA")
    then do:
     for first code_mstr
        where code_mstr.code_domain  = global_domain
        and   code_mstr.code_fldname = "XX_PAYREFSEPA"
        and   code_mstr.code_value   = tt_tCInvoiceCIAPM.tcCInvoiceTSMNumber
     no-lock:
       
     end.
     if not available code_mstr
     then do:
        create api_status.
        assign api_status.data_seq     = 0
               api_status.return_status  = "FAILED"
               api_status.message_type = "Pre-validation"
               api_status.message_string  = gettermlabel("INVOICE_TYPE",8) + gettermlabel("DOES_NOT_EXIST",6)                                       
               api_status.traceid = vc_traceid. 
     end.
     
     end. /*  if can-find first(code_mstr */
     
     
     
     for each tt_tAPMatchingCIAPM no-lock
        where tt_tAPMatchingCIAPM.tc_ParentRowid = tt_tCInvoiceCIAPM.tc_Rowid:
        
        
        /* Purchase Order */
        for first po_mstr 
           where po_domain   = global_domain
           and   po_nbr      = tt_tAPMatchingCIAPM.tcPurchaseOrderNumber
        no-lock:
        end.
        
        if not available po_mstr
        then do:
        
        create api_status.
        assign api_status.data_seq     = 0
               api_status.return_status  = "FAILED"
               api_status.message_type = "Pre-validation"
               api_status.message_string  = gettermlabel("PO",8) + gettermlabel("DOES_NOT_EXIST",6)                                       
               api_status.traceid = vc_traceid. 
               
        end.
        else if po_vend <> tt_tCInvoiceCIAPM.tcCreditorCode
        then do:
        
        create api_status.
        assign api_status.data_seq     = 0
               api_status.return_status  = "FAILED"
               api_status.message_type = "Pre-validation"
               api_status.message_string  = gettermlabel("SUPPLIER_CODE",8) + gettermlabel("NON_CONFORMITY_REASON",3)                                       
               api_status.traceid = vc_traceid. 
        end.
        
        /* Receiver */
        for first prh_hist
               where prh_domain   = global_domain
               and   prh_nbr      = tt_tAPMatchingCIAPM.tcPurchaseOrderNumber
               and   prh_receiver = tt_tAPMatchingCIAPM.tcReceiverNumber 
               and   prh_line     = tt_tAPMatchingCIAPM.tiPurchaseOrderLineNumber
            no-lock:
            end.
            
            if not available prh_hist
            then do:
                           
               /*Invalid receiver*/
                  create api_status.
                  assign api_status.data_seq     = 0
                         api_status.return_status  = "FAILED"
                         api_status.message_type = "Pre-validation"
                         api_status.message_string  = gettermlabel("RECEIVER",8) + gettermlabel("DOES_NOT_EXIST",3)                                       
                         api_status.traceid = vc_traceid. 

            end. /*NOT AVAILABLE prh_hist*/
            
            if available prh_hist
            then do:
               if prh_rcvd < decimal(tt_tAPMatchingCIAPM.tdMatchQty)
               then do:
                  /*1247 Invalid invoice quantity for quantity received*/
                  create api_status.
                  assign api_status.data_seq     = 0
                         api_status.return_status  = "FAILED"
                         api_status.message_type = "Pre-validation"
                         api_status.message_string  = gettermlabel("RECEIVED_QTY",8) + gettermlabel("INSUFFICIENT_QTY",2)                                       
                         api_status.traceid = vc_traceid. 
               end.
               
               /*
               if decimal(tt_tAPMatchingCIAPM.tdMatchUnitPrice ) = 0
               then do:
                  /*7513 Invoice price cannot be zero*/
                  create api_status.
                  assign api_status.data_seq     = 0
                         api_status.return_status  = "FAILED"
                         api_status.message_type = "Pre-validation"
                         api_status.message_string  = gettermlabel("RECEIVED_QTY",8) + gettermlabel("INSUFFICIENT_QTY",2)                                       
                         api_status.traceid = vc_traceid. 
               end.
               */
         
            end. /* if available prh_hist */
                   
        
    end. /* for each tt_tAPMatchingCIAPM no-lock */
     
  end. /*EACH tCInvoiceCIAPM Data*/


  /** if validation passed and not import invoice **/
  if  vl_RetOK and not can-find(first api_status no-lock where api_status.return_status  = "FAILED" )
  then do:		 
		 
		 for each tt_tCInvoiceCIAPM where tt_tCInvoiceCIAPM.tc_Status = "N" 
                                  break by tt_tCInvoiceCIAPM.tc_Rowid:
                  
                  empty temp-table tFcMessages.
                  empty temp-table tAPMatchingCIAPM.
                  empty temp-table tCInvoiceCIAPM.
                  empty temp-table tAPMatchingCostCIAPM.       

                  create tCInvoiceCIAPM.
                  buffer-copy tt_tCInvoiceCIAPM to tCInvoiceCIAPM.
                 
       for each tt_tAPMatchingCIAPM no-lock where tt_tAPMatchingCIAPM.tc_ParentRowid = tCInvoiceCIAPM.tc_Rowid.
                                            
                                             
                  create tAPMatchingCIAPM.
                  buffer-copy tt_tAPMatchingCIAPM to tAPMatchingCIAPM.
       end. /* for each tt_tAPMatchingCIAPM  */
		
      for each tt_tAPMatchingCostCIAPM no-lock where tt_tAPMatchingCostCIAPM.tc_ParentRowid = tCInvoiceCIAPM.tc_Rowid.
                                               
                       
                 create tAPMatchingCostCIAPM.
                 buffer-copy tt_tAPMatchingCostCIAPM to tAPMatchingCostCIAPM.
      end. /*  for each tt_tAPMatchingCostCIAPM */
			
                                
                  run proxy/bcinvoiceapmatching.p persistent set vhProxyComponent.
         
                  run ApiMaintainByDatasetWithOutput in vhProxyComponent
                  (input  tt_tCInvoiceCIAPM.tcCompanyCode,
                     input  "save",
                     input  true,
                     input  true,
                     input  icPartialUpdateExceptionList,
                     input  dataset BCInvoiceAPMatching by-reference,
                     output ocPrimaryKey,
                     output ocRowid,
                     output oiDraftInstance,
                     output ocPrimaryKeyName,
                     output dataset-handle vho,
                     output dataset tFcMessages,
                     output oiReturnStatus).
                    
                 
          for each tFcMessages :

				     if tFCMessages.tcFcType = "W" then next.  

                     if index(tFcMessages.tcFcMessage,"warning") <> 0 or
                     index(tFcMessages.tcFcMessage, "The sum of the base and tax amounts") <> 0 then
                     next.
                     
                     if index(tFcMessages.tcFcMsgNumber, "qadfin-500498") <> 0 then
                     next.
                     
                     if index(tFcMessages.tcFcMsgNumber, "QadFin-8125") <> 0 then
                     next.
                                         
                     assign
                        v_errorstatus  = yes.
                       
                     
                     if tFcMessages.tcFcFieldName <> "" then
                     do:
                      create api_status.
                      assign api_status.data_seq     = 0
                             api_status.return_status  = "FAILED"
                             api_status.message_type = "API_ERROR"
                             api_status.message_string  = gettermlabel("SEVERITY",8) + " = " +
                                                          string(tFcMessages.tiFcSeverity) + " | " +
                                                          tFcMessages.tcFcMessage + " | " +
                                                          gettermlabel("FIELD_NAME",10) + " = " +
                                                          tFcMessages.tcFcFieldName + " | " +
                                                          gettermlabel("FIELD_LABEL",11) + " = " +
                                                          tFcMessages.tcFcFieldLabel + " | " +
                                                          gettermlabel("FIELD_VALUE",11) + " = " +
                                                          tFcMessages.tcFcFieldValue + " | " +
                                                          tFcMessages.tcFcMsgNumber
                             api_status.dataid  = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_dataid                                        
                             api_status.traceid = vc_traceid. 
                     end.
                    
                     else
                     do:
                      create api_status.
                      assign api_status.data_seq     = 0
                             api_status.return_status  = "FAILED"
                             api_status.message_type = "API_ERROR"
                             api_status.message_string  = gettermlabel("SEVERITY",8) + " = " +
                                                          string(tFcMessages.tiFcSeverity) + " | " +
                                                          tFcMessages.tcFcMessage + " | " +
                                                          tFcMessages.tcFcMsgNumber
                             api_status.dataid  = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_dataid                                        
                             api_status.traceid = vc_traceid. 
                     end. /* else do */
                     
                     
                  end. /* for each tFcMessages : */
       
                  delete procedure vhProxyComponent.
				 
                  if not v_errorstatus then 
                  do:
				         
                     find usr where usr.UsrLogin =   tt_tCInvoiceCIAPM.tCInvoiceCIAPM_userid no-lock no-error.
                                          
                      
                      
                      
                     for first Cinvoice
                     where string(CInvoice_ID) = string(ocPrimaryKey)
                     exclusive-lock: 
                     
                     if tt_tCInvoiceCIAPM.tCInvoiceCIAPM_userid  <> "" and available usr 
                     then cinvoice.LastModifiedUser =  tt_tCInvoiceCIAPM.tCInvoiceCIAPM_userid .
                     
                     assign                    
                     Cinvoice.CInvoiceDescription    = substring(tt_tCInvoiceCIAPM.tcCInvoiceRemark,1,40,"RAW")
                     Cinvoice.CInvoiceCommentNote    = tt_tCInvoiceCIAPM.tcCInvoiceRemark
                     cinvoice.CInvoiceHoldAmountTC   = 0. 

                     end. /*for first Cinvoice*/
                     find journal of Cinvoice no-lock no-error.
                     for first cinvoiceposting where string(cinvoiceposting.cinvoice_id) = string(ocPrimaryKey):
                     find first posting where posting.posting_id = cinvoiceposting.posting_id no-error.
                     if avail posting then
                     do:
                     assign  postingtext = tt_tCInvoiceCIAPM.tcCInvoiceRemark .
                     
                     if avail usr then 
                     assign posting.CreatorUsr_ID = usr.usr_id.
                     
                     
                     end.
                     create api_status.
                      assign api_status.data_seq     = 1
                             api_status.return_status  = "SUCCESS"
                             api_status.message_type = Cinvoice.CInvoiceReference
                             api_status.message_string  = string(CInvoicePostingYear) + "/" + 
                                                          journal.journalcode + "/" + 
                                                          string(Cinvoice.cinvoicevoucher,"999999999") 
                                                        
                             api_status.dataid  = tt_tCInvoiceCIAPM.tCInvoiceCIAPM_dataid                                        
                             api_status.traceid = vc_traceid. 
                  end.  /* if not v_toterrorstatus then  */   

        end. /* CIMLOOP*/
	
       end. /*for each tt_tCInvoiceCIAPM exclusive-lock*/       
  end.  /*IF vl_RetOK AND vc_import then  do :*/


   
         /* Handle cimload related files */
         /* Create output json */                
         
         run writejsonfile(input hresult,
                  input vc_outputjson,
                  input "FILE",
                  input True,
                  input "UTF-8",
                  output vl_RetOK,
                  output vc_errorstring).
                  
         put unformatted v_cim " " skip
                         v_log " " skip 
                         m_outpath " " skip
                         m_archpath " " skip
                         v_runproagram " " skip
                         v_errstring " " skip 
                         v_errorstatus skip .
                         
                         
       do vi_filecount = 1 to 5:
          /* when success move cim log file to archive directory  */
          /* when failed move cim log file to error directory  */   
          /*  move status json file to out directory for API return */   
          /* when success move previous step .p and json file to archive directory  */
          /* when failed move previous step .p and json file to error directory  */       
          case vi_filecount:
      
          when 1 then
          assign vc_filename = replace(vc_inputjson,".json",".p")
                 vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
          when 2 then
          assign vc_filename = vc_inputjson
                 vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
          when 3 then
          assign vc_filename = replace(vc_inputjson,".json",".dat")
                 vc_topath   = if v_errorstatus then m_errorpath else m_archpath. 
          when 4 then
          assign vc_filename = replace(vc_inputjson,".json",".run.log")
                 vc_topath   = m_outpath.
          when 5 then
          assign vc_filename = replace(vc_inputjson,".json",".run.out.json")
                 vc_topath   =  m_outpath.
          end case.
          
         if vl_RetOK then 
         put unformatted vc_filename " " skip
         vc_topath " " skip 
         vi_filecount skip.
     
        
          
          run cimfilehandle(input vc_filename,
                            input vc_topath,
                            input no ).                 
                   
          
     
       end.       /* do vi_filecount = 1 to 5: */        
       

   
   for each tt_tCInvoiceCIAPM.
   export tt_tCInvoiceCIAPM.
   end.   
   
   for each tt_tAPMatchingCIAPM.
   export tt_tAPMatchingCIAPM.
   end.

   for each tt_tAPMatchingCostCIAPM.
   export tt_tAPMatchingCostCIAPM.
   end.
   for each tt_CInvoiceAdditional.
   export tt_CInvoiceAdditional.
   end.
   put oiReturnStatus skip.
  
  output close.
   
   leave.
   
end. /* repeat */


procedure getTaxDet:
   
   define input  parameter v_input1      as character.
   define input  parameter v_input2      as character.
   define input  parameter v_taxUsage    as character.
   define input  parameter v_tax_class   as character.
   define input  parameter v_pointdate   as date.
   define input  parameter v_taxable     as logical.
   define output parameter v_taxEnv      as character.
   define output parameter v_taxType     as character.
   define output parameter v_taxRate     as decimal.
   define output parameter v_vatCode     as character.
   define output parameter v_taxAccount  as character.
   define output parameter m_from        as character.
   define output parameter m_to          as character.
   define output parameter v_taxCode     as character.
   define output parameter v_taxCNaccount     as character.
   
   define variable m_from1        as character.
   
   def buffer bf_ad_mstr for ad_mstr.
   
   assign
      v_taxEnv    = ""
      v_taxType   = ""
      v_taxRate   = 0
      v_vatCode   = ""
      v_taxAccount= ""
      m_from1 = ""
      v_taxCNaccount = ""
      .
  
   for first creditor no-lock
      where creditorcode = v_input1,
      first businessrelation of creditor,
      first address of businessrelation:
      m_from = address.TxzTaxZone.
   end.
   
   for first company no-lock
      where companycode = v_input2 ,
      first companyproperty of company,
      first businessrelation of companyproperty,
      first address of businessrelation:
      m_to = address.TxzTaxZone.
   end.
   

   
   m_from1 = m_from.
   
   if v_tax_class  <> "" then
   do:
      substring(m_from1,17) = v_tax_class.
   end.
   
   
  
   for first txe_mstr no-lock
      where txe_zone_from = m_from1
      and txe_zone_to   = m_to:
   end.
   if available txe_mstr then
   do:
      v_taxEnv = txe_desc.
      
      for first txed_det no-lock
         where txed_tax_env = txe_desc:
      end.
      if available txed_det then
      do:
         for first vd_mstr no-lock
            where vd_domain = global_domain
            and vd_addr   = v_input1:
         end.
         if available vd_mstr and v_taxable then
         do:
            for last tx2_mstr no-lock
               where tx2_domain    = global_domain
               and tx2_tax_type  = txed_tax_type
               and tx2_pt_taxc   = v_tax_class
               and tx2_tax_usage = v_taxUsage
               and ((tx2_effdate <= v_pointdate and tx2_exp_date = ?)
               or (tx2_effdate <= v_pointdate  and tx2_exp_date >= v_pointdate)):
              
            end.
           
            if available tx2_mstr then
            do:
               assign
                  v_taxType     = tx2_tax_type
                  v_taxRate     = tx2_tax_pct
                  v_taxAccount  = tx2_ap_acct
                  v_taxCNaccount = tx2_ap_cn_acct
                  v_taxCode     = tx2_tax_code
                  .
            end.
         end.
         else
         do:
            for last tx2_mstr no-lock
               where tx2_domain    = global_domain
               and tx2_tax_type  = v_noTax
               and tx2_effdate   < today:
            end.
            if available tx2_mstr then
            do:
           
               assign
                  v_taxType     = tx2_tax_type
                  v_taxRate     = tx2_tax_pct
                  v_taxAccount  = tx2_ap_acct
                  v_taxCNaccount = tx2_ap_cn_acct
                  v_taxCode     = tx2_tax_code
                  .
            end.
         end.
      end.
   end.
   
   for first creditor no-lock
      where creditorcode = v_input1,
      first txu_mstr where creditor.txutaxusage = txu_tax_usage,
      first domains  where domaincode = GLOBAL_DOMAIN,      
      first vat where vat.domain_id   = domains.domain_id   
      and vat.txutaxusage = txu_tax_usage:
      v_vatCode = vatcode.
   end.
   if v_vatCode = "" then
   v_vatCode = v_taxCode.
   
end.






